package com.open.capacity.reimburse.controller;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.reimburse.excel.BudgetExcelModel;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import com.open.capacity.reimburse.entity.PbdBudget;
import com.open.capacity.reimburse.service.PbdBudgetService;

import com.open.capacity.commons.PageResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 年度预算表
 *
 * @author
 * @email
 * @date 2021-03-11 10:08:47
 */
@RestController
@RequestMapping("pbdbudgets")
@Api(tags = "年度预算表")
public class PbdBudgetController {

    @Autowired
    private PbdBudgetService pbdBudgetService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = pbdBudgetService.pageAll(params);
        return pageResult;
    }

    /**
     * 查询单条记录
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:list')")
    public Result findById(String id) {
        return Result.succeed(pbdBudgetService.findById(id));
    }

    /**
     * 保存
     */
    @RequestMapping("/saveOrUpdate")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:save')")
    @LogAnnotation(module = "年度预算", name = "保存")
    public Result save(@RequestBody @Valid PbdBudget pbdBudget, String keyValue) {
        if (StringUtils.isEmpty(keyValue)) {
            pbdBudgetService.save(pbdBudget);
        } else {
            pbdBudget.setId(keyValue);
            pbdBudgetService.update(pbdBudget);
        }
        return Result.succeed("保存成功");
    }


    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:delete')")
    @LogAnnotation(module = "年度预算", name = "删除")
    public Result delete(@PathVariable String id) {
        pbdBudgetService.delete(id);
        return Result.succeed("删除成功");
    }

    /**
     * 导入excel
     */
    @PostMapping("/importExcel")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:import')")
    public Result importExcel(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        int count = pbdBudgetService.importExcel(multipartFile);
        return Result.succeed(count, "导入成功");
    }

    /**
     * 导出数据
     */
    @GetMapping("/exportExcel")
    @PreAuthorize("hasAnyAuthority('bd_budget:bdbudget:export')")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        List<PbdBudget> list = pbdBudgetService.findAll(params);

        List<BudgetExcelModel> result = list.stream().map(item -> {
            BudgetExcelModel model = new BudgetExcelModel();
            BeanUtils.copyProperties(item, model);
            return model;
        }).collect(Collectors.toList());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=bdbudget.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("预算信息", "预算"),
                BudgetExcelModel.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
